<template>
  <div class="page-content parking-list">
    <!-- 页面标题和说明 -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold">停车场管理</h1>
      <p class="text-gray-500 mt-2">管理景区内所有停车场信息及车位状态</p>
    </div>

    <!-- 操作栏 -->
    <el-row justify="space-between" :gutter="10" class="mb-6">
      <el-col :lg="12" :md="12" :sm="14" :xs="16">
        <div class="flex gap-2">
          <el-button type="primary" @click="toAddParkingLot">
            <el-icon><Plus /></el-icon>添加停车场
          </el-button>
          <el-input
            v-model="searchVal"
            :prefix-icon="Search"
            clearable
            placeholder="输入停车场名称查询"
            style="width: 250px"
            @keyup.enter="searchParkingLots"
          />
        </div>
      </el-col>
      <el-col :lg="12" :md="12" :sm="0" :xs="0">
        <div class="custom-segmented flex justify-end">
          <el-radio-group v-model="statusFilter" size="default" @change="filterByStatus">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="open">营业中</el-radio-button>
            <el-radio-button label="full">已满</el-radio-button>
            <el-radio-button label="closed">已关闭</el-radio-button>
          </el-radio-group>
        </div>
      </el-col>
    </el-row>

    <!-- 数据概览 -->
    <el-row :gutter="20" class="mb-6">
      <el-col :md="6" :sm="12" :xs="24" class="mb-4">
        <el-card
          shadow="hover"
          class="h-full bg-gradient-to-r from-blue-50 to-blue-100 dark:from-blue-900 dark:to-blue-800"
        >
          <div class="flex items-center">
            <div class="p-2 rounded-full bg-blue-500 text-white mr-4">
              <i class="i-carbon-car-front text-2xl"></i>
            </div>
            <div>
              <div class="text-gray-500 text-sm">总停车场</div>
              <div class="text-xl font-bold">{{ statistics.totalParkingLots }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :md="6" :sm="12" :xs="24" class="mb-4">
        <el-card
          shadow="hover"
          class="h-full bg-gradient-to-r from-green-50 to-green-100 dark:from-green-900 dark:to-green-800"
        >
          <div class="flex items-center">
            <div class="p-2 rounded-full bg-green-500 text-white mr-4">
              <i class="i-carbon-checkbox-checked text-2xl"></i>
            </div>
            <div>
              <div class="text-gray-500 text-sm">总车位</div>
              <div class="text-xl font-bold">{{ statistics.totalSpaces }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :md="6" :sm="12" :xs="24" class="mb-4">
        <el-card
          shadow="hover"
          class="h-full bg-gradient-to-r from-yellow-50 to-yellow-100 dark:from-yellow-900 dark:to-yellow-800"
        >
          <div class="flex items-center">
            <div class="p-2 rounded-full bg-yellow-500 text-white mr-4">
              <i class="i-carbon-car text-2xl"></i>
            </div>
            <div>
              <div class="text-gray-500 text-sm">已占用车位</div>
              <div class="text-xl font-bold">{{ statistics.occupiedSpaces }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :md="6" :sm="12" :xs="24" class="mb-4">
        <el-card
          shadow="hover"
          class="h-full bg-gradient-to-r from-red-50 to-red-100 dark:from-red-900 dark:to-red-800"
        >
          <div class="flex items-center">
            <div class="p-2 rounded-full bg-red-500 text-white mr-4">
              <i class="i-carbon-pedestrian text-2xl"></i>
            </div>
            <div>
              <div class="text-gray-500 text-sm">可用车位</div>
              <div class="text-xl font-bold">{{ statistics.availableSpaces }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 停车场列表 -->
    <el-row :gutter="20">
      <el-col
        :xs="24"
        :sm="12"
        :md="8"
        :lg="6"
        v-for="item in parkingLots"
        :key="item.id"
        class="mb-5"
      >
        <el-card :body-style="{ padding: '0px' }" shadow="hover" class="parking-card">
          <!-- 骨架屏 -->
          <el-skeleton animated :loading="isLoading" style="width: 100%">
            <template #template>
              <div style="padding-top: 56.25%"></div>
              <!-- 16:9 占位 -->
              <div style="padding: 14px">
                <el-skeleton-item variant="h3" style="width: 80%" />
                <div style="display: flex; align-items: center; margin-top: 8px">
                  <el-skeleton-item variant="text" style="margin-right: 16px" />
                  <el-skeleton-item variant="text" style="width: 30%" />
                </div>
                <el-skeleton-item variant="text" style="width: 100%; margin-top: 16px" />
                <el-skeleton-item variant="text" style="width: 100%; margin-top: 8px" />
              </div>
            </template>

            <template #default>
              <div class="relative">
                <el-image
                  class="parking-image"
                  :src="item.imageUrl || 'https://picsum.photos/600/300?random=' + item.id"
                  fit="cover"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="absolute top-2 right-2">
                  <el-tag :type="getStatusType(item.status)" size="large" effect="dark">
                    {{ item.status }}
                  </el-tag>
                </div>
              </div>

              <div class="p-4">
                <div class="flex justify-between items-start">
                  <h3 class="text-lg font-medium">{{ item.name }}</h3>
                </div>
                <div class="text-sm text-gray-500 mt-2 flex items-center">
                  <el-icon><Location /></el-icon>
                  <span class="ml-1">{{ item.location }}</span>
                </div>
                <div class="mt-3 flex justify-between">
                  <div class="progress-container">
                    <el-progress
                      :percentage="getOccupancyPercentage(item)"
                      :color="getProgressColor(item)"
                      :format="
                        () => `${item.totalSpaces - item.availableSpaces}/${item.totalSpaces}`
                      "
                      :stroke-width="10"
                    />
                  </div>
                </div>
                <div class="mt-3 text-sm grid grid-cols-2 gap-2">
                  <div class="text-gray-500">营业时间：</div>
                  <div class="text-gray-700">{{ item.openingHours }}</div>
                  <div class="text-gray-500">收费标准：</div>
                  <div class="text-gray-700">{{ item.fee.hourly }}元/小时</div>
                </div>
                <div class="flex justify-between items-center mt-4">
                  <div>
                    <el-button type="primary" text size="small" @click.stop="viewDetail(item)">
                      查看详情
                    </el-button>
                    <el-button type="primary" text size="small" @click.stop="editParkingLot(item)">
                      编辑
                    </el-button>
                  </div>
                </div>
              </div>
            </template>
          </el-skeleton>
        </el-card>
      </el-col>
    </el-row>

    <!-- 空状态 -->
    <div style="margin-top: 16vh" v-if="showEmpty">
      <el-empty description="暂无停车场数据" />
    </div>

    <!-- 分页器 -->
    <div class="flex justify-center mt-6">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[8, 16, 24, 36]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :hide-on-single-page="false"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted } from 'vue'
  import { router } from '@/router'
  import { Search, Picture, Location, Plus } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import type { ParkingLotType } from '@/types/parking'
  import { ParkingLotStatus } from '@/types/parking'

  // 状态过滤器
  const statusFilter = ref('all')

  // 搜索值
  const searchVal = ref('')

  // 停车场列表数据
  const parkingLots = ref<ParkingLotType[]>([])

  // 分页相关
  const currentPage = ref(1)
  const pageSize = ref(8)
  const total = ref(0)
  const isLoading = ref(true)

  // 空状态判断
  const showEmpty = computed(() => {
    return parkingLots.value.length === 0 && !isLoading.value
  })

  // 统计数据
  const statistics = ref({
    totalParkingLots: 0,
    totalSpaces: 0,
    occupiedSpaces: 0,
    availableSpaces: 0
  })

  // 获取状态标签类型
  const getStatusType = (status: string) => {
    switch (status) {
      case ParkingLotStatus.OPEN:
        return 'success'
      case ParkingLotStatus.FULL:
        return 'warning'
      case ParkingLotStatus.MAINTENANCE:
        return 'info'
      case ParkingLotStatus.CLOSED:
        return 'danger'
      default:
        return ''
    }
  }

  // 获取车位占用百分比
  const getOccupancyPercentage = (parkingLot: ParkingLotType): number => {
    if (parkingLot.totalSpaces === 0) return 0
    return Math.round(
      ((parkingLot.totalSpaces - parkingLot.availableSpaces) / parkingLot.totalSpaces) * 100
    )
  }

  // 根据占用百分比获取进度条颜色
  const getProgressColor = (parkingLot: ParkingLotType): string => {
    const percentage = getOccupancyPercentage(parkingLot)
    if (percentage >= 90) return '#F56C6C' // 红色
    if (percentage >= 70) return '#E6A23C' // 黄色
    return '#67C23A' // 绿色
  }

  // 组件挂载时获取数据
  onMounted(() => {
    getParkingLots()
  })

  // 获取停车场列表
  const getParkingLots = async () => {
    isLoading.value = true

    try {
      // 模拟API请求延迟
      setTimeout(() => {
        const data = generateMockData()
        parkingLots.value = data
        total.value = data.length > 8 ? 100 : data.length // 模拟总数
        updateStatistics()

        isLoading.value = false
      }, 1000)

      // 实际API调用示例:
      // const res = await parkingService.getParkingLots({
      //   page: currentPage.value,
      //   pageSize: pageSize.value,
      //   status: statusFilter.value !== 'all' ? statusFilter.value : undefined,
      //   keyword: searchVal.value || undefined
      // })
      // if (res.code === 200) {
      //   parkingLots.value = res.data.records
      //   total.value = res.data.total
      //   updateStatistics()
      // }
    } catch (error) {
      console.error('获取停车场列表失败', error)
      isLoading.value = false
    }
  }

  // 更新统计数据
  const updateStatistics = () => {
    const totalParkingLots = parkingLots.value.length
    let totalSpaces = 0
    let availableSpaces = 0

    parkingLots.value.forEach((parking) => {
      totalSpaces += parking.totalSpaces
      availableSpaces += parking.availableSpaces
    })

    statistics.value = {
      totalParkingLots,
      totalSpaces,
      availableSpaces,
      occupiedSpaces: totalSpaces - availableSpaces
    }
  }

  // 生成模拟数据
  const generateMockData = () => {
    const statusMap = {
      all: [
        ParkingLotStatus.OPEN,
        ParkingLotStatus.FULL,
        ParkingLotStatus.MAINTENANCE,
        ParkingLotStatus.CLOSED
      ],
      open: [ParkingLotStatus.OPEN],
      full: [ParkingLotStatus.FULL],
      maintenance: [ParkingLotStatus.MAINTENANCE],
      closed: [ParkingLotStatus.CLOSED]
    }

    const statuses = statusMap[statusFilter.value] || statusMap.all

    const locations = ['景区东门', '景区西区', '景区北门', '中心广场', '山腰', '南区商业街']
    const names = [
      '东门停车场',
      '西区停车场',
      '北门停车场',
      '中心停车场',
      '山顶停车场',
      '游客中心停车场',
      '员工停车场',
      'VIP停车场',
      '临时停车场',
      '南区停车场'
    ]

    return Array.from({ length: 8 }, (_, i) => {
      const randomId = (currentPage.value - 1) * pageSize.value + i + 1
      const randomName = names[Math.floor(Math.random() * names.length)]
      const randomLocation = locations[Math.floor(Math.random() * locations.length)]
      const randomStatus = statuses[Math.floor(Math.random() * statuses.length)]

      const totalSpaces = Math.floor(Math.random() * 200) + 50 // 50-250之间的随机车位数
      const randomAvailability = Math.random() // 0-1之间的随机可用率
      const availableSpaces =
        randomStatus === ParkingLotStatus.FULL ? 0 : Math.floor(totalSpaces * randomAvailability)

      // 如果有搜索关键词，则过滤
      if (searchVal.value && !randomName.includes(searchVal.value)) {
        return null
      }

      return {
        id: randomId,
        name: `${randomName}${randomId}`,
        location: randomLocation,
        totalSpaces,
        availableSpaces,
        status: randomStatus,
        fee: {
          hourly: Math.floor(Math.random() * 10) + 5, // 5-15元/小时
          daily: Math.floor(Math.random() * 50) + 50 // 50-100元/天
        },
        openingHours: '24小时开放',
        imageUrl: `https://picsum.photos/600/300?random=${randomId}`,
        description: '这是一个设施完善的停车场，提供安全监控、照明和导航标识等服务。',
        features: ['24小时开放', '视频监控', '充电桩', '残疾人车位'],
        contactPhone: '1234567890',
        createTime: '2023-01-01 00:00:00',
        updateTime: '2023-01-01 00:00:00'
      }
    }).filter(Boolean) // 过滤掉null值
  }

  // 查看详情
  const viewDetail = (item: ParkingLotType) => {
    router.push({
      path: `/parking/detail`,
      query: {
        id: item.id
      }
    })
  }

  // 编辑停车场
  const editParkingLot = (item: ParkingLotType) => {
    router.push({
      path: `/parking/edit`,
      query: {
        id: item.id
      }
    })
  }

  // 添加新停车场
  const toAddParkingLot = () => {
    router.push({
      path: `/parking/edit`
    })
  }

  // 搜索停车场
  const searchParkingLots = () => {
    currentPage.value = 1
    getParkingLots()
  }

  // 状态过滤
  const filterByStatus = () => {
    currentPage.value = 1
    getParkingLots()
  }

  // 处理页码大小变化
  const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
    getParkingLots()
  }

  // 处理页码变化
  const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getParkingLots()
  }
</script>

<style lang="scss" scoped>
  .parking-list {
    .parking-card {
      height: 100%;
      transition: transform 0.3s;

      &:hover {
        transform: translateY(-5px);
        box-shadow:
          0 10px 15px -3px rgba(0, 0, 0, 0.1),
          0 4px 6px -2px rgba(0, 0, 0, 0.05);
      }

      .parking-image {
        width: 100%;
        height: 180px;
        object-fit: cover;

        .image-slot {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 100%;
          height: 100%;
          background: var(--el-fill-color-light);
          color: var(--el-text-color-secondary);
          font-size: 30px;
        }
      }

      .progress-container {
        width: 100%;
      }
    }
  }
</style>
